<template>
  <div class="app-container">
    <div class="device-box">
      <el-card v-for="device in list" :key="device.id" class="box-card">
        <div slot="header" class="clearfix">
          <div class="device-info">
            <span style="font-size:12px"> {{ device.name }} </span>
            <span style="font-size:12px"> {{ device.power }} V </span>
            <span style="font-size:12px"> {{ device.position }} </span>
            <span style="font-size:12px"> {{ device.sn }} </span>
          </div>
          <el-breadcrumb separator="/" style="float: right;">
            <el-button type="text" size="small" @click.stop="toOnlineLog(device.sn)">在线记录</el-button>
            <el-button type="text" size="small" @click.stop="toPowerLog(device.sn)">电量记录</el-button>
            <el-button type="text" size="small" @click.stop="toOperateLog(device.sn)">操作记录</el-button>
          </el-breadcrumb>
        </div>
        <div v-for="tap in device.taps" :key="tap.id" class="text item">
          <el-row>
            <el-col :span="8"> <span style="font-size:15px"> {{ tap.alias }} </span> </el-col>
            <el-col :span="8">
              <span v-if="tap.status == 0" style="font-size:15px;color:red;"> 已关闭 </span>
              <span v-else-if="tap.status == 1" style="font-size:15px;color:green;"> 已开启 </span>
              <span v-else-if="tap.status == 2" style="font-size:15px;color:red;"> 半开 </span>
              <span v-else-if="tap.status == 3" style="font-size:15px;color:green;"> 开启中 </span>
              <span v-else-if="tap.status == 4" style="font-size:15px;color:red;"> 关闭中 </span>
              <span v-else style="font-size:15px;color:red;"> 异常 </span>
            </el-col>
            <el-col :span="4"> <el-button size="small" type="success" round @click.stop="openTap(device, tap)">打开</el-button> </el-col>
            <el-col :span="4"> <el-button size="small" type="danger" round @click.stop="closeTap(device, tap)">关闭</el-button> </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

  </div>
</template>

<script>
import { deviceList, devicePositionList } from '@/api/userapi/device'
import waves from '@/directive/waves' // waves directive

export default {
  name: 'Find',
  directives: { waves },
  data() {
    return {
      value: true,
      tableKey: 0,
      list: [],
      listLoading: true,
      total: 10,
      listQuery: {
        name: null,
        position: null,
        page: 1,
        limit: 20
      },
      positions: [],
      dialogFormVisible: false,
      formLabelWidth: '100px',
      form: {
        sn: null,
        name: null,
        position: null,
        power: null,
        taps: null
      }
    }
  },
  created() {
    this.getPositionList()
    this.fetchData()
  },
  methods: {
    dateFormat(time) {
      var date = new Date(time)
      var year = date.getFullYear()
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1
      var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var hours =
        date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes =
        date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      // 拼接
      return (
        year +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hours +
        ':' +
        minutes +
        ':' +
        seconds
      )
    },
    fetchData() {
      this.listLoading = true
      if (this.listQuery.datetimeStart) {
        this.listQuery.datetimeStart = this.dateFormat(
          this.listQuery.datetimeStart
        )
      }
      if (this.listQuery.datetimeEnd) {
        this.listQuery.datetimeEnd = this.dateFormat(
          this.listQuery.datetimeEnd
        )
      }
      deviceList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data.items
        this.total = response.data.total
        this.doSubscribe()
        console.log(this.list)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    getPositionList() {
      devicePositionList().then(response => {
        this.positions = response.data.items
        console.log(this.positions)
      })
    },
    toOnlineLog(sn) {
      this.$router.push({
        path: '/log/online',
        query: { sn }
      })
    },
    toPowerLog(sn) {
      console.log('电量记录')
      this.$router.push({
        path: '/log/power',
        query: { sn }
      })
    },
    toOperateLog(sn) {
      this.$router.push({
        path: '/log/operate',
        query: { sn }
      })
    },

    // mqtt相关操作
    doSubscribe() {
      var devices = this.list
      for (var i = 0; i < devices.length; i++) {
        var topic = 'tap/' + devices[i].sn + '/pub/#'
        console.log('订阅消息')
        console.log(topic)
        this.$mqtt.subscribe(topic)
      }
    },
    subscribe(val) {
      this.$mqtt.subscribe(val)
    },
    publish(topic, message) {
      this.$mqtt.publish(topic, message)
    },
    openTap(device, tap) {
      if (!device.online) {
        this.$message.error('当前设备[' + tap.sn + ']不在线,无法操作')
      }
      var topic = 'tap/' + device.sn + '/sub' + '/sw' + tap.number
      this.$mqtt.publish(topic, 'ON')
    },
    closeTap(device, tap) {
      if (!device.online) {
        this.$message.error('当前设备[' + tap.sn + ']不在线,无法操作')
      }
      var topic = 'tap/' + device.sn + '/sub' + '/sw' + tap.number
      this.$mqtt.publish(topic, 'OFF')
    }
  },
  mqtt: {
    'tap/#'(data, topic) {
      console.log(topic + ': ' + String.fromCharCode.apply(null, data))
      var devices = this.list
      var patt = /^tap\/([a-zA-Z0-9]{8,10})\/pub\/(\S+)/
      var res = patt.exec(topic)
      if (res) {
        var sn = res[1]
        var type = res[2]
        for (var i = 0; i < devices.length; i++) {
          if (devices[i].sn === sn) {
            if (type === 'online') {
              devices[i].online = parseInt(data)
              break
            }
            if (type === 'sta1') {
              devices[i].status1 = parseInt(data)
              break
            }
            if (type === 'sta2') {
              devices[i].status2 = parseInt(data)
              break
            }
            if (type === 'pow') {
              devices[i].power = parseFloat(data).toFixed(3)
              break
            }
            if (type === 'info') {
              var info = JSON.parse(data)
              devices[i].status1 = parseInt(info['sta1'])
              devices[i].status2 = parseInt(info['sta2'])
              devices[i].power = parseFloat(info['pow']).toFixed(2)
              devices[i].online = 1
              break
            }
          }
        }
      }
    }
  }
}
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.device-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  align-items: center;
}
.device-info {
  height: 50px;
  width: 100%;
  align-items: center;
  order: solid 0.5px #B0B0B0;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.box-card {
  width: 48%;
  margin-top: 10px;
}

</style>
